package com.mysoft.gfyx.marketdevelop.service.impl;

import com.alibaba.fastjson.JSON;
import com.mysoft.framework.common.exception.BusinessLogicException;
import com.mysoft.framework.modeling.dto.*;
import com.mysoft.framework.service.AppService;
import com.mysoft.gfyx.common.util.MyStringUtil;
import com.mysoft.gfyx.marketdevelop.controller.dto.GetDetailDataRequestDto;
import com.mysoft.gfyx.marketdevelop.mip.GetDeveloperDataService;
import com.mysoft.gfyx.marketdevelop.mip.agent.GetProjectDataServiceAgent;
import com.mysoft.gfyx.marketdevelop.mip.dto.*;
import com.mysoft.gfyx.marketdevelop.mip.dto.TjCustom.ResponseDataDto;
import com.mysoft.gfyx.marketdevelop.service.*;
import com.mysoft.gfyx.marketdevelop.service.dto.AdFieldOptionResponseDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class DeveloperTakeLandServiceImp extends BaseDataApiServiceImp implements DeveloperTakeLandService {
    @Autowired
    private DeveloperService developerService;

    @Autowired
    private GetDeveloperDataService getDeveloperDataService;

    @Autowired
    private LoadDataApiCommonService loadDataApiCommonService;

    @Autowired
    private GetProjectDataServiceAgent getProjectDataServiceAgent;

    @Autowired
    private LabelService labelService;

    @Autowired
    private ProvinceRadarService provinceRadarService;

    @Autowired
    private CommonService commonService;

    public FieldsSetting loadFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("uuid");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "developer_take_land";
        fieldsSetting.getFields().add(new DataApiField("uuid", groupName, "RowID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("id", groupName, "股权拿地ID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("take_land_id", groupName, "拿地ID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_name", groupName, "拿地企业", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("sub_developer_name", groupName, "拿地企业(子公司)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("organizing_code", groupName, "社会统一信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("take_land_price", groupName, "成交价格（万元）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("take_land_date", groupName, "拿地日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("land_usage", groupName, "土地类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("land_usage_category", groupName, "土地标签分类", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("all_area", groupName, "总面积(平米)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("planned_area", groupName, "规划总建面积(平米)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province", groupName, "区域（省）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_code", groupName, "区域（省）Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city", groupName, "区域（市）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city_code", groupName, "区域（市）Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("land_address", groupName, "地址", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("land_title", groupName, "土地名称", FieldType.String));


        // 返回
        return fieldsSetting;
    }

    public ListDataResult loadData(LoadDataParams options) {
        String creditCode = options.getOptions().getContext().get("id").toString();
        GetDeveloperFilterDataRequestDto dto = new GetDeveloperFilterDataRequestDto();

        dto = developerService.setCommonData(dto, DeveloperService.TjEntity.TakingLand);
        dto.setDetail_table_name(DeveloperService.TABLE_TAKE_LAND_WITH_INVESTMENT);
        //dto.setIdentity_value(creditCode);
        dto.setPage(options.getPageIndex() + 1);
        dto.setPage_size(options.getPageSize());

        List<Filter> filters = options.getOptions().getFilters();
        filters = labelService.setLandUsageLabel(filters, "land_usage");
        FilterProvince(filters);
        loadDataApiCommonService.setDefaultDeveloperWithoutInvestment(filters, creditCode);
        dto.addFilterByLoadDataApi(filters, DeveloperService.TABLE_TAKE_LAND_WITH_INVESTMENT, new HashMap<String, String>() {{
            put("land_usage", DeveloperService.TABLE_TAKE_LAND_USAGE);
        }});

        // 排序
        ArrayList<GetDeveloperSortDto> sorts = new ArrayList<>();
        GetDeveloperSortDto sort = new GetDeveloperSortDto();
        sort.setSort_type(GetDeveloperSortDto.SORT_DESC);
        sort.setAttribute_name("take_land_date");
        sort.setTable_name(DeveloperService.TABLE_TAKE_LAND_WITH_INVESTMENT);
        sorts.add(sort);
        dto.setSorts(sorts);

        BaseTjListResponseDto res = getDeveloperDataService.getFilteredDeveloperDetailList(dto);

        return developerService.getTjResFromLoadData(res);
    }

    public void FilterProvince(List<Filter> filters) {
        if (filters.size() > 0) {
            for (int i = 0; i < filters.size(); i++) {
                if (filters.get(i).getCondition().size() > 0 && filters.get(i).getCondition().get(0).getField().equals("province_code") && filters.get(i).getCondition().get(0).getValue().equals("0")) {
                    filters.remove(i);
                }
            }
        }
    }

    public Map<String, Object> getLandDetail(GetDetailDataRequestDto dto) {
        //拿地详情
        GetDeveloperFilterDataRequestDto requestDto = new GetDeveloperFilterDataRequestDto();
        requestDto = developerService.setCommonData(requestDto);
        requestDto.setDetail_table_name(DeveloperService.TABLE_TAKE_LAND_ALL);
        requestDto.setPage(1);
        requestDto.setPage_size(1);
        requestDto.addFilterDtos("id", BaseTjFilterDto.OPERATE_EQUAL, dto.getId(), DeveloperService.TABLE_TAKE_LAND_ALL, BaseTjFilterDto.ASSOCIATE_NONE);
        BaseTjListResponseDto res = getDeveloperDataService.getFilteredDeveloperDetailList(requestDto);
        if (res.getData().getList() == null || res.getData().getList().size() == 0) {
            throw new BusinessLogicException("未找到土地信息");
        }

        Map<String, Object> data = res.getData().getList().get(0).getItem();
        //拿地公司和顶级公司
        if (data.get("organizing_code") != null) {
            Map<String, Object> companyData = developerService.getDeveloperMainData(data.get("organizing_code").toString());
            data.put("company", companyData);

            if (companyData.get("is_top_company_contain_developer") != null && companyData.get("top_organizing_code") != null && companyData.get("is_top_company_contain_developer").equals("是")) {
                Map<String, Object> topCompanyData = developerService.getDeveloperMainData(companyData.get("top_organizing_code").toString());
                data.put("topCompany", topCompanyData);
            }
        }

        //联系人数量
        if (data.get("organizing_code") != null && !data.get("organizing_code").equals("")) {
            GetDeveloperContactsRequestDto getDeveloperContactsRequestDto = new GetDeveloperContactsRequestDto();
            getDeveloperContactsRequestDto.setDeveloper_organizing_code(data.get("organizing_code").toString());
            getDeveloperContactsRequestDto.setPageSize(100000);
            Map<String, Integer> contactCount = provinceRadarService.getContactCount(getDeveloperContactsRequestDto);
            data.put("contact_num", contactCount.getOrDefault(data.get("organizing_code").toString(), 0));
        } else {
            data.put("contact_num", 0);
        }

        //数据状态
        if (data.get("id") != null) {
            data.put("oppty_status", commonService.getOpptyStatus(CommonService.BigDataType.LAND.toString(), data.get("id").toString(), true));
        }
        return data;
    }

    public List<AdFieldOptionResponseDto> getOptions() {
        List<AdFieldOptionResponseDto> options = new ArrayList<>();
        ResponseDataDto res = getProjectDataServiceAgent.getLandTypeData();
        if (res.getRows().size() < 1) {
            return options;
        }
        res.getRows().forEach(r -> {
            AdFieldOptionResponseDto item = new AdFieldOptionResponseDto();
            String parentValue = r.get("category").toString();
            item.setItemCode(parentValue);
            item.setItemName(parentValue);
            item.setParentCode("0");
            options.add(item);
            List<String> subItems = JSON.parseArray(r.get("land_usage").toString(), String.class);
            subItems.forEach(t -> {
                if (!t.equals(parentValue)) {
                    AdFieldOptionResponseDto subItem = new AdFieldOptionResponseDto();
                    subItem.setParentCode(parentValue);
                    subItem.setItemName(t);
                    subItem.setItemCode(t);
                    options.add(subItem);
                }
            });
        });
        return options;
    }

}
